<?php

namespace app\api\logic;

use app\common\model\AnswerQuestion;
use think\facade\Db;

class Statistics
{
    /**
     * 获取用户某专业答题量
     * @param int $userId
     * @param int $profession_id
     * @return int
     */
    public function getUserAnswerCount(int $userId, int $profession_id): int
    {
        //查询条件
        $where = [
            ['user_id', '=', $userId],
        ];
        $subSql = app(\app\common\model\ProfessionCourse::class)->field('course_id')->where(['profession_id' => $profession_id])->buildSql();
        $where[] = ['', 'exp', Db::raw("course_id in$subSql")];

        //返回
        return app(AnswerQuestion::class)->where($where)->count();
    }

    /**
     * 获取用户某专业答题正确率
     * @param int $userId
     * @param int $profession_id
     * @return int
     */
    public function getUserCorrectCount(int $userId, int $profession_id): int
    {
        //查询条件
        $where = [
            ['user_id', '=', $userId],
            ['status', '=', 1],
        ];
        $subSql = app(\app\common\model\ProfessionCourse::class)->field('course_id')->where(['profession_id' => $profession_id])->buildSql();
        $where[] = ['', 'exp', Db::raw("course_id in$subSql")];

        //返回
        return app(AnswerQuestion::class)->where($where)->count();
    }

    /**
     * 获取首页统计
     * @param $param
     * @return array
     */
    public function getIndexData($param): array
    {
        //提取参数
        $userId = $param['userId'] ?? 0;
        $profession_id = $param['profession_id'];

        //构建统计
        if ($userId && $profession_id)
        {
            $count = $this->getUserAnswerCount($userId, $profession_id);
            $correct_count = $this->getUserCorrectCount($userId, $profession_id);
        }
        else
        {
            $count = 0;
            $correct_count = 0;
        }

        //返回
        return [
            'day' => 100,
            'exam_day' => '距离2021-04-11考试',
            'count' => $count,
            'correct' => $count > 0 ? round(($correct_count / $count) * 100) : 0,
            'list' => [
                [
                    'title' => '距离2021-04-11考试',
                    'day' => 100,
                ]
            ]
        ];
    }
}